const { prisma } = require('../config/prisma');
const bcrypt = require('bcrypt');

/**
 * 管理员模型类 - Prisma版本
 */
class AdministratorPrisma {
  constructor(data) {
    this.id = data.id;
    this.username = data.username;
    this.password = data.password;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  /**
   * 根据用户名查找管理员
   * @param {string} username 用户名
   * @returns {Promise<AdministratorPrisma|null>}
   */
  static async findByUsername(username) {
    const admin = await prisma.administrators.findUnique({
      where: { username }
    });
    return admin ? new AdministratorPrisma(admin) : null;
  }

  /**
   * 根据ID查找管理员
   * @param {number} id 管理员ID
   * @returns {Promise<AdministratorPrisma|null>}
   */
  static async findById(id) {
    const admin = await prisma.administrators.findUnique({
      where: { id: parseInt(id) }
    });
    return admin ? new AdministratorPrisma(admin) : null;
  }

  /**
   * 创建新管理员
   * @param {Object} data 管理员数据
   * @returns {Promise<AdministratorPrisma>}
   */
  static async create(data) {
    const { username, password } = data;
    
    // 密码加密
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash(password, saltRounds);
    
    const admin = await prisma.administrators.create({
      data: {
        username,
        password: hashedPassword
      }
    });
    
    return new AdministratorPrisma(admin);
  }

  /**
   * 验证密码
   * @param {string} password 明文密码
   * @returns {Promise<boolean>}
   */
  async verifyPassword(password) {
    return await bcrypt.compare(password, this.password);
  }

  /**
   * 更新管理员信息
   * @param {number} id 管理员ID
   * @param {Object} data 更新数据
   * @returns {Promise<AdministratorPrisma>}
   */
  static async update(id, data) {
    const updateData = {};
    
    if (data.username) {
      updateData.username = data.username;
    }
    
    if (data.password) {
      const saltRounds = 10;
      const hashedPassword = await bcrypt.hash(data.password, saltRounds);
      updateData.password = hashedPassword;
    }
    
    if (Object.keys(updateData).length === 0) {
      throw new Error('没有要更新的字段');
    }
    
    const admin = await prisma.administrators.update({
      where: { id: parseInt(id) },
      data: updateData
    });
    
    return new AdministratorPrisma(admin);
  }

  /**
   * 删除管理员
   * @param {number} id 管理员ID
   * @returns {Promise<boolean>}
   */
  static async delete(id) {
    await prisma.administrators.delete({
      where: { id: parseInt(id) }
    });
    return true;
  }

  /**
   * 获取管理员列表
   * @param {Object} options 查询选项
   * @returns {Promise<Object>}
   */
  static async getList(options = {}) {
    const { page = 1, pageSize = 10 } = options;
    
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const skip = (pageNum - 1) * pageSizeNum;
    
    // 并行查询总数和列表数据
    const [total, admins] = await Promise.all([
      prisma.administrators.count(),
      prisma.administrators.findMany({
        select: {
          id: true,
          username: true,
          created_at: true,
          updated_at: true
          // 不选择password字段
        },
        orderBy: { created_at: 'desc' },
        skip,
        take: pageSizeNum
      })
    ]);
    
    return {
      data: admins.map(admin => new AdministratorPrisma(admin)),
      pagination: {
        page: pageNum,
        pageSize: pageSizeNum,
        total,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    };
  }

  /**
   * 获取管理员统计信息
   * @returns {Promise<Object>}
   */
  static async getStats() {
    const total = await prisma.administrators.count();
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const todayCount = await prisma.administrators.count({
      where: {
        created_at: {
          gte: today
        }
      }
    });

    return { total, today: todayCount };
  }

  /**
   * 转换为JSON格式（不包含密码）
   * @returns {Object}
   */
  toJSON() {
    return {
      id: this.id.toString(),
      username: this.username,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}

module.exports = AdministratorPrisma;
